package cn.com.lsy.product.lepao.filter;

import cn.com.lsy.product.lepao.response.base.ApiResponseEnum;
import cn.com.lsy.product.lepao.response.base.BaseRet;
import cn.com.lsy.product.lepao.util.BodyReaderHttpServletRequestWrapper;
import cn.com.lsy.product.lepao.util.CheckSignUtil;
import cn.com.lsy.product.lepao.util.CheckTokenUtil;
import cn.com.lsy.product.lepao.util.HttpHelper;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.DigestException;

public class CheckSignFilter implements Filter {

    private static String resultCode = "0";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(req);
        String body = HttpHelper.getBodyString(requestWrapper);
        // 自己拦截的逻辑

        BaseRet<String> ret = new BaseRet<String>();

        try {

            boolean result = CheckSignUtil.check(body, req.getHeader("sign"));

            if (result) {

                String uri = req.getRequestURI();
                if (uri.indexOf("doAuth") > 0) {

                    String token = req.getHeader("token");
                    String roleType = req.getHeader("roleType");
                    if (StringUtils.isEmpty(token)) {
                        onAccessFailAsTokeniSNull(req, response);
                    } else if (StringUtils.isEmpty(roleType)) {
                        onAccessFailAsRoleTypeiSNull(req, response);
                    } else {

                        String status = CheckTokenUtil.check(token, roleType);
                        if (status.equals("1")) {
                            // 继续把流写出去，避免控制器无法获取参数情况
                            arg2.doFilter(requestWrapper, response);
                        } else {

                            resultCode = status;
                            onAccessFail(req, response);
                        }

                    }

                } else {

                    // 继续把流写出去，避免控制器无法获取参数情况
                    arg2.doFilter(requestWrapper, response);
                }

            } else {

                ret.setMsg("非法请求!");
                ret.setCode(ApiResponseEnum.API_RESPONSE_ILLEGAL);

            }


        } catch (DigestException e) {

            e.printStackTrace();

            ret.setMsg("非法请求!");
            ret.setCode(ApiResponseEnum.API_RESPONSE_ILLEGAL);

        }

        if (!StringUtils.isEmpty(ret.getMsg())) {

            Gson gson = new Gson();
            String str = gson.toJson(ret);

            byte[] dataByteArr = str.getBytes("UTF-8");

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(dataByteArr);
        }

    }

    @Override
    public void destroy() {

    }

    public void onAccessFailAsTokeniSNull(HttpServletRequest request, HttpServletResponse response) {
        // 使用输出流
        try {

            BaseRet<String> ret = new BaseRet<String>();
            ret.setMsg("Token不能为空!");
            ret.setCode(ApiResponseEnum.API_RESPONSE_TOKEN_NULL);

            Gson gson = new Gson();
            String str = gson.toJson(ret);

            byte[] dataByteArr = str.getBytes("UTF-8");

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(dataByteArr);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void onAccessFailAsRoleTypeiSNull(HttpServletRequest request, HttpServletResponse response) {
        // 使用输出流
        try {

            BaseRet<String> ret = new BaseRet<String>();
            ret.setMsg("角色类型不能为空!");
            ret.setCode(ApiResponseEnum.API_RESPONSE_TOKEN_NULL);

            Gson gson = new Gson();
            String str = gson.toJson(ret);

            byte[] dataByteArr = str.getBytes("UTF-8");

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(dataByteArr);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void onAccessFailAsDeviSNull(HttpServletRequest request, HttpServletResponse response) {
        // 使用输出流
        try {

            BaseRet<String> ret = new BaseRet<String>();
            ret.setMsg("设备ID不能为空!");
            ret.setCode(ApiResponseEnum.API_RESPONSE_TOKEN_NULL);

            Gson gson = new Gson();
            String str = gson.toJson(ret);

            byte[] dataByteArr = str.getBytes("UTF-8");

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(dataByteArr);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void onAccessFail(HttpServletRequest request, HttpServletResponse response) {

        // 使用输出流
        try {

            BaseRet<String> ret = new BaseRet<String>();
            ret.setMsg("登录已失效!");
            ret.setCode(ApiResponseEnum.API_RESPONSE_TOKEN_ERROR);
            if (resultCode.equals("-1")) {
                ret.setMsg("您的账号已被禁用!");
                ret.setCode(ApiResponseEnum.API_RESPONSE_DISABLE);
            }

            Gson gson = new Gson();
            String str = gson.toJson(ret);

            byte[] dataByteArr = str.getBytes("UTF-8");

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(dataByteArr);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
